<?php
/**
 * 权限控制
 * User zgh
 * Email 1803897171@qq.com
 * Date 2021/7/17
 **/

namespace app\common\service;


use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
use EasyAdmin\tool\CommonTool;
use think\facade\Env;
use think\facade\Request;

class AuthService
{
    /**
     * 获取当前请求的节点
     * 节点的 格式  module.controller(controller驼峰转下划线)/action
     */
    public static function getCurrentNode()
    {
        $node = Request::module() . "." . Request::controller() . "/" . Request::action();
        return self::parseNodeStr($node);
    }

    /**
     * 获取当前的控制器
     */
    public static function getCurrentControllerClass()
    {
        $name = "app\\" . Request::module() . "\\controller\\" . Request::controller() . "Controller";
        return $name;
    }

    /**
     * 驼峰转下划线规则
     * @param $node
     */
    public static function parseNodeStr($node)
    {
        $array = explode('/', $node);
        foreach ($array as $key => $val) {
            if ($key == 0) {
                $val = explode('.', $val);
                foreach ($val as &$vo) {
                    $vo = parse_name($vo);
                }
                $val = implode('.', $val);
                $array[$key] = $val;
            }
        }
        $node = implode('/', $array);
        return $node;
    }

    protected static function replacePath($path)
    {
        $path = str_replace('\\', '/', $path);
        $path = str_replace('//', '/', $path);
        return rtrim($path, "/");
    }

    /**
     * 获取所有控制器
     * @return array
     */
    public static function getControllerList($path)
    {
        list($list, $temp_list) = [[], scandir($path)];
        foreach ($temp_list as $file) {
            // 排除根目录和没有开启注解的模块
            if ($file == ".." || $file == ".") {
                continue;
            }
            if (is_file($path . DIRECTORY_SEPARATOR . $file) && strrpos(strtolower($file), "controller") !== false) {
                $className = realpath($path . DIRECTORY_SEPARATOR . $file);
                $className = str_replace('.php', '', $className);
                $className = self::replacePath($className);
                $className = "app" . substr($className, strpos($className, "application") + strlen("application"));
                $className = str_replace("/", "\\", $className);
                $list[] = $className;
            }
        }
        return $list;
    }


}